package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"test/common"
	"test/dto"
	"test/model"
	"time"
)

func Register(ctx *gin.Context) {
	DB := common.GetDB()
	requestUser := make(map[string]interface{})
	//获取参数
	var student model.Students
	DB.Last(&student)
	ctx.ShouldBind(&requestUser)
	sno:=student.Sno + 1
	sname:=requestUser["username"].(string)
	sdate:= time.Now().Add(7 * 24 * time.Hour).Format("2006-01-02 15:02:05")
	spassword:=requestUser["password"].(string)
	spayment := 0
	if isSnoExists(DB,sname) {
		ctx.JSON(200,gin.H{
			"code": 200,
			"msg": "学生已经存在",
		})
		fmt.Println("我执行了")
		return
	}
	newStudent := model.Students{
		Sno: sno,
		Sname:    sname,
		Sdate: 	  sdate,
		Spayment: spayment,
		Spassword: spassword,
	}
	DB.Create(&newStudent)
	//返回结果
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "注册成功",
	})
}

func StudentLogin(ctx *gin.Context) {
	//获取参数
	DB := common.GetDB()
	requestUser := make(map[string]interface{})
	ctx.ShouldBind(&requestUser)
	fmt.Println(requestUser)
	sname:=requestUser["username"].(string)
	password:=requestUser["password"].(string)
	//判断姓名是否存在
	var student model.Students
	DB.Where("sname = ?",sname).First(&student)
	if student.Sno == 0 {
		fmt.Println("我执行了")
		ctx.JSON(200, gin.H{
			"code":200,
			"msg":"用户不存在",
		})
	}
	//判断密码是否正确
	DB.Where("password = ?",password).First(&student)
	if  student.Sno == 0{
		fmt.Println("我执行了")
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"密码错误"})
		return
	}
	//返回结果
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg": "登录成功",
	})
}
func Info(ctx *gin.Context) {
	user,_:= ctx.Get("people")
	ctx.JSON(http.StatusOK,gin.H{"code":200,"data":gin.H{"people":dto.ToUserDto(user.(model.Students))}})
}

func isSnoExists(db *gorm.DB,sname string) bool {//string
	var student model.Students
	db.Where("sname = ?",sname).First(&student)
	if student.Sno != 0 {
		return true
	} else {
		return false
	}
}
